package com.forum.Controller;

import com.common.Entity.Result;
import com.common.Utils.JwtUtil;
import com.forum.Entity.Comment;
import com.forum.Entity.Post;
import com.forum.Service.CommentService;
import com.forum.Service.PostService;
import com.forum.Service.SysService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;

@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private SysService sysService;

    @Autowired
    private PostService postService;

    @GetMapping("/getComments/{postId}")
    public Result getComments(@PathVariable("postId") String postId) {
        List<Comment> list = commentService.getComments(postId);
        return Result.success(list);
    }

    @GetMapping("/getCommentsByPost")
    public Result getCommentsByPost(@RequestParam Integer pageNum,
                                    @RequestParam Integer pageSize,
                                    @RequestParam String postId,
                                    @RequestParam(required = false) String content) {
        PageInfo<Comment> pageInfo =  commentService.getCommentsByPost(pageNum, pageSize, postId,content);
        return Result.success(pageInfo);
    }

    @PostMapping("/addComment")
    public Result addComment(@RequestBody Comment comment) {
        String token = comment.getToken();
        String username = JwtUtil.extractUsername(token);
        comment.setCreateUser(username);
        comment.setCreateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));

        //远程调用
        String userId =sysService.getUserByName(username);
        comment.setUserId(userId);
        commentService.addComment(comment);
        postService.addComments(comment.getPostId());
        return Result.success();
    }

    @PostMapping("/addReply")
    public Result addReply(@RequestBody Comment comment) {
        String token = comment.getToken();
        String username = JwtUtil.extractUsername(token);
        comment.setCreateUser(username);
        comment.setCreateTime(LocalDateTime.now(ZoneId.of("Asia/Shanghai")));
        //远程调用
        String userId =sysService.getUserByName(username);
        comment.setUserId(userId);
        commentService.addReply(comment);
        return Result.success();
    }

    @DeleteMapping("/deleteComment/{commentId}")
    public Result deleteComment(@PathVariable("commentId") String commentId) {
        commentService.deleteComment(commentId);
        return Result.success();
    }

}
